/*
 * Copyright (c) Mirth Corporation. All rights reserved.
 * 
 * http://www.mirthcorp.com
 * 
 * The software in this package is published under the terms of the MPL license a copy of which has
 * been included with this distribution in the LICENSE.txt file.
 */

package com.mirth.connect.client.ui.browsers.event;

import java.awt.Dimension;
import java.awt.Point;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.mirth.connect.client.ui.MirthDialog;
import com.mirth.connect.client.ui.UIConstants;
import com.mirth.connect.client.ui.util.DisplayUtil;
import com.mirth.connect.model.ServerEvent.Outcome;

public class EventBrowserAdvancedFilter extends MirthDialog {

    private Map<Integer, String> userMapById;
    private Map<String, Integer> userMapByName;
    private static Map<String, Object> cachedSettings;

    public EventBrowserAdvancedFilter(com.mirth.connect.client.ui.Frame parent, String title, boolean modal, Map<Integer, String> userMap) {
        super(parent, title, modal);

        initComponents();
        getContentPane().setBackground(new java.awt.Color(255, 255, 255));

        pack();
        Dimension dlgSize = getPreferredSize();
        Dimension frmSize = parent.getSize();
        Point loc = parent.getLocation();

        if ((frmSize.width == 0 && frmSize.height == 0) || (loc.x == 0 && loc.y == 0)) {
            setLocationRelativeTo(null);
        } else {
            setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
        }

        DisplayUtil.setResizable(this, false);

        cachedSettings = new HashMap<String, Object>();

        // Cache the user map by both names and ids for easy lookup
        // The first items in the map are [-1, ALL] and [0, System]
        userMapById = userMap;
        userMapByName = new LinkedHashMap<String, Integer>();

        for (Entry<Integer, String> entry : userMapById.entrySet()) {
            userMapByName.put(entry.getValue(), entry.getKey());
        }

        userComboBox.setModel(new javax.swing.DefaultComboBoxModel(userMapById.values().toArray()));

        String[] outcomeValues = new String[Outcome.values().length + 1];
        outcomeValues[0] = UIConstants.ALL_OPTION;
        for (int i = 1; i < outcomeValues.length; i++) {
            outcomeValues[i] = Outcome.values()[i - 1].toString();
        }

        outcomeComboBox.setModel(new javax.swing.DefaultComboBoxModel(outcomeValues));

        reset();
    }

    public void reset() {
        userComboBox.setSelectedIndex(0);
        outcomeComboBox.setSelectedIndex(0);
        ipAddressField.setText("");
    }

    @Override
    public void setVisible(boolean visible) {
        if (visible) {
            saveSelections();
        }

        super.setVisible(visible);
    }

    public void saveSelections() {
        cachedSettings.clear();

        cachedSettings.put("user", userComboBox.getSelectedItem());
        cachedSettings.put("outcome", outcomeComboBox.getSelectedItem());
        cachedSettings.put("ipAddress", ipAddressField.getText());
    }

    public void loadSelections() {
        userComboBox.setSelectedItem((String) cachedSettings.get("user"));
        outcomeComboBox.setSelectedItem((String) cachedSettings.get("outcome"));
        ipAddressField.setText((String) cachedSettings.get("ipAddress"));

        cachedSettings.clear();
    }

    public Boolean hasAdvancedCriteria() {
        Boolean hasAdvancedCriteria = false;

        if (userComboBox.getSelectedIndex() != 0 || outcomeComboBox.getSelectedIndex() != 0 || StringUtils.isNotEmpty(ipAddressField.getText())) {
            hasAdvancedCriteria = true;
        }

        return hasAdvancedCriteria;
    }

    public Integer getUser() {
        Integer user = userMapByName.get((String) userComboBox.getSelectedItem());

        return user;
    }

    public String getOutcome() {
        return (String) outcomeComboBox.getSelectedItem();
    }

    public String getIpAddress() {
        return ipAddressField.getText();
    }

    public String getServerId() {
        return serverIdField.getText();
    }

    @Override
    public void onCloseAction() {
        formWindowClosing(null);
    }

    // @formatter:off
    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT
     * modify this code. The content of this method is always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        userLabel = new javax.swing.JLabel();
        userComboBox = new javax.swing.JComboBox();
        ipAddressField = new com.mirth.connect.client.ui.components.MirthTextField();
        ipAddressLabel = new javax.swing.JLabel();
        outcomeLabel = new javax.swing.JLabel();
        outcomeComboBox = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        cancelButton = new javax.swing.JButton();
        okButton1 = new javax.swing.JButton();
        serverIdField = new com.mirth.connect.client.ui.components.MirthTextField();
        serverIdLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        userLabel.setText("User:");

        ipAddressLabel.setText("IP Address:");

        outcomeLabel.setText("Outcome:");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        cancelButton.setText("Cancel");
        cancelButton.setMargin(new java.awt.Insets(0, 2, 0, 2));
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        okButton1.setText("OK");
        okButton1.setMargin(new java.awt.Insets(0, 2, 0, 2));
        okButton1.setMaximumSize(new java.awt.Dimension(48, 21));
        okButton1.setMinimumSize(new java.awt.Dimension(48, 21));
        okButton1.setPreferredSize(new java.awt.Dimension(48, 21));
        okButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(okButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelButton))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 6, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(okButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        serverIdLabel.setText("Server ID:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(outcomeLabel)
                    .addComponent(userLabel)
                    .addComponent(ipAddressLabel)
                    .addComponent(serverIdLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(outcomeComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(userComboBox, 0, 125, Short.MAX_VALUE)
                        .addComponent(ipAddressField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(serverIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(56, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userLabel)
                    .addComponent(userComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(outcomeLabel)
                    .addComponent(outcomeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ipAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ipAddressLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serverIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(serverIdLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // @formatter:on

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        loadSelections();
    }//GEN-LAST:event_formWindowClosing

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        loadSelections();

        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void okButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButton1ActionPerformed

        setVisible(false);
    }//GEN-LAST:event_okButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private com.mirth.connect.client.ui.components.MirthTextField ipAddressField;
    private javax.swing.JLabel ipAddressLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton okButton1;
    private javax.swing.JComboBox outcomeComboBox;
    private javax.swing.JLabel outcomeLabel;
    private com.mirth.connect.client.ui.components.MirthTextField serverIdField;
    private javax.swing.JLabel serverIdLabel;
    private javax.swing.JComboBox userComboBox;
    private javax.swing.JLabel userLabel;
    // End of variables declaration//GEN-END:variables
}
